@extends('layouts.base')

@section('title', '子分类管理')

@push('styles')
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            /*border-radius: 10px;*/
            /*margin-bottom: 20px;*/
            position: relative;
        }

        .page-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin: 0;
            text-align: center;
        }

        .category-tabs {
            display: flex;
            background: white;
            border-radius: 0;
            /*margin-bottom: 20px;*/
            overflow: hidden;
            box-shadow: none;
            border-bottom: 1px solid #e2e8f0;
        }

        .category-tab {
            flex: 1;
            padding: 12px;
            background: white;
            border: none;
            font-size: 1rem;
            font-weight: 500;
            color: #666;
            cursor: pointer;
            transition: all 0.2s;
        }

        .category-tab.active {
            background: #667eea;
            color: white;
        }

        .category-content {
            background: white;
            border-radius: 0;
            padding: 20px;
            box-shadow: none;
        }

        .category-list::-webkit-scrollbar {
            width: 6px;
        }

        .category-list::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 3px;
        }

        .category-list::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }

        .category-list::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        .category-section {
            display: none;
        }

        .category-section.active {
            display: block;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }

        .section-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
        }

        .add-category-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: background 0.2s;
        }

        .add-category-btn:hover {
            background: #218838;
        }

        .list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e2e8f0;
        }

        .list-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .add-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: background 0.2s;
        }

        .add-btn:hover {
            background: #218838;
        }

        .category-list {
            list-style: none;
            padding: 0;
            margin: 0;
            background: none;
        }

        .category-item {
            /*padding: 16px 20px;*/
            margin-bottom: 8px;
            /*background: white;*/
            /*border: 1px solid #e2e8f0;*/
            /*border-radius: 8px;*/
            display: ruby;
            align-items: center;
            transition: all 0.2s ease;
            cursor: move;
            background: none;
            /*box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);*/
        }
        .category-item:hover {
            background: none;
        }

        .category-info {
            display: flex;
            align-items: center;
            flex: 1;
            gap: 12px;
        }

        .drag-handle {
            color: #999;
            cursor: move;
            font-size: 18px;
            width: 24px;
            text-align: center;
            flex-shrink: 0;
        }

        .drag-handle:hover {
            color: #667eea;
        }

        .category-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            background: #f0f4ff;
            border: 1px solid #e2e8f0;
            flex-shrink: 0;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .category-icon:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .category-name {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin: 0;
            flex: 1;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 6px;
            transition: background-color 0.2s;
            line-height: 1.4;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .category-name:hover {
            background-color: #f0f4ff;
        }

        .name-text {
            font-size: 16px;
            font-weight: 500;
            color: #333;
        }

        .subcategory-count {
            font-size: 12px;
            color: #666;
            font-weight: 400;
        }

        .category-actions {
            display: flex;
            gap: 8px;
            flex-shrink: 0;
        }

        .action-btn {
            width: 36px;
            height: 36px;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            transition: all 0.2s ease;
            background: white;
            color: #666;
        }

        .edit-btn {
            background-color: #48bb78;
            color: white;
            border-color: #48bb78;
        }

        .edit-btn:hover {
            background-color: #38a169;
            border-color: #38a169;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
        }

        .delete-btn {
            background-color: #f56565;
            color: white;
            border-color: #f56565;
        }

        .delete-btn:hover {
            background-color: #e53e3e;
            border-color: #e53e3e;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(245, 101, 101, 0.3);
        }

        .subcategory-btn {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }

        .subcategory-btn:hover {
            background-color: #5a67d8;
            border-color: #5a67d8;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #4a5568;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* 图标选择器样式 */
        .icon-selector {
            position: relative;
        }

        .selected-icon {
            width: 60px;
            height: 60px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            background: white;
            transition: all 0.2s ease;
        }

        .selected-icon:hover {
            border-color: #667eea;
            background: #f0f4ff;
        }

        .icon-picker {
            position: absolute;
            top: 70px;
            left: 0;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            width: 280px;
        }

        .icon-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 8px;
        }

        .icon-option {
            width: 40px;
            height: 40px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            cursor: pointer;
            transition: all 0.2s ease;
            background: white;
        }

        .icon-option:hover {
            border-color: #667eea;
            background: #f0f4ff;
            transform: scale(1.1);
        }

        .icon-option.selected {
            border-color: #667eea;
            background: #667eea;
            color: white;
        }

        .modal-test {
            top: 300px;
        }
    </style>
@endpush

@section('content')
<div class="">
    <!-- 页面头部 -->
    <div class="page-header">
        <button class="back-btn" onclick="window.location.href = '{{ route('user.books.categories', ['book' => $book['id']]) }}'">
            ← 返回
        </button>
        <h1 class="page-title">【{{ $category->name }}】分类管理</h1>
{{--        <p class="page-subtitle" id="category-subtitle">{{ $category->name }}</p>--}}
    </div>

    <!-- 子类别迁移模态框 -->
    <div class="modal fade" id="subcategory-migration-modal" tabindex="-1" role="dialog" aria-labelledby="subcategoryMigrationModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content modal-test">
                <div class="modal-header">
                    <h5 class="modal-title" id="subcategoryMigrationModalLabel">迁移子类别交易记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p id="subcategory-migration-message"></p>
                    <div class="form-group">
                        <label for="target-category-select">选择目标分类：</label>
                        <select class="form-control" id="target-category-select">
                            <option value="">请选择目标分类</option>
                        </select>
                    </div>
                    <div class="form-group" id="target-subcategory-container" style="display: none;">
                        <label for="target-subcategory-select">选择目标子类别：</label>
                        <select class="form-control" id="target-subcategory-select">
                            <option value="">请选择目标子类别</option>
                        </select>
                        <input type="hidden" id="source-subcategory-id" value="">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="migrateAndDeleteSubcategory()">确认迁移并删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 分类内容 -->
    <div class="category-content">
        <div class="section-header">
            <h2 class="section-title">子分类列表</h2>
            <button class="add-category-btn" onclick="showAddSubcategoryModal()">+ 添加子分类</button>
        </div>
        <div class="category-list-container">
            <ul class="category-list" id="subcategory-list">
                <!-- 动态加载子分类 -->
            </ul>
            <div class="empty-state" id="empty-state" style="display: none;">
                <div class="empty-state-icon">📂</div>
                <div class="empty-state-text">暂无子分类</div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑子分类弹窗 -->
<div class="modal fade" id="subcategoryModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-test">
            <div class="modal-header">
                <h5 class="modal-title" id="subcategoryModalTitle">添加子分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="subcategory-form">
                    <div class="form-group">
                        <label class="form-label">子分类名称</label>
                        <input type="text" class="form-input" id="subcategory-name" placeholder="请输入子分类名称" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">描述说明（描述可以让AI分类得更精准的）</label>
                        <input type="text" class="form-input" id="subcategory-description" placeholder="格式：xx和xx费用（可选）">
                    </div>
                    <div class="form-group">
                        <label class="form-label">选择图标</label>
                        <div class="icon-selector">
                            <input type="text" class="form-input" id="emoji-search" placeholder="输入中文搜索图标...">
                            <div class="emoji-selector" id="emoji-selector">
                            </div>
                            <div class="emoji-option-no-results" style="display: none" id="emoji-selector-empty">-- 没有找到匹配的emoji --</div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-subcategory">确定</button>
            </div>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script src="{{ asset('/js/sortable.min.js') }}"></script>
<script src="{{ asset('js/emoji-search.js') }}"></script>
<script>
        $(document).ready(function() {
            // 加载子分类数据
            loadSubcategories();

            // 确认添加/编辑子分类
            $('#confirm-subcategory').click(function() {
                if (currentSubcategoryId) {
                    updateSubcategory();
                } else {
                    createSubcategory();
                }
            });

            // 初始化拖拽排序
            initSortable();
        });

        const bookId = {{ $book->id }};
        const categoryId = {{ $category->id }};
        let currentSubcategoryId = null;
        let selectedIcon = '📁';
        let sortable = null;

        // 返回上一页
        function goBack() {
            window.location.href = `{{ route('user.books.categories', $book->id) }}`;
        }

        // 加载子分类数据
        function loadSubcategories() {
            $.get(`{{ route('user.subcategories.data', [$book->id, $category->id]) }}`, function(response) {
                if (response.success) {
                    renderSubcategories(response.subcategories);
                } else {
                    showMessage('加载子分类失败', 'error');
                }
            }).fail(function() {
                showMessage('网络错误，请重试', 'error');
            });
        }

        // 渲染子分类列表
        function renderSubcategories(subcategories) {
            const subcategoryList = $('#subcategory-list');
            const emptyState = $('#empty-state');

            subcategoryList.empty();

            if (subcategories.length === 0) {
                emptyState.show();
                subcategoryList.hide();
            } else {
                emptyState.hide();
                subcategoryList.show();

                subcategories.forEach(function(subcategory) {
                    const subcategoryHtml = createSubcategoryHtml(subcategory);
                    subcategoryList.append(subcategoryHtml);
                });

                // 重新初始化拖拽排序
                initSortable();
            }
        }

        // 创建子分类HTML
        function createSubcategoryHtml(subcategory) {
            const icon = subcategory.icon || '📁';

            // 安全地转义字符串
            const escapedName = subcategory.name.replace(/'/g, "\\'").replace(/"/g, '\\"');
            const escapedDesc = (subcategory.description || '').replace(/'/g, "\\'").replace(/"/g, '\\"');

            return `
                <li style="display: block">
                <div class="category-item" data-id="${subcategory.id}" data-icon="${icon}" data-name="${subcategory.name}" data-desc="${escapedDesc}">
                    <div class="drag-handle">⋮⋮</div>
                    <div class="category-info">
                        <div class="category-icon">${icon}</div>
                        <div class="category-name" onclick="editSubcategoryById(${subcategory.id})">
                            <span class="name-text">${subcategory.name}</span>
                        </div>
                    </div>
                    <div class="category-actions">
                        <button class="action-btn edit-btn" onclick="editSubcategoryById(${subcategory.id})" title="编辑子分类">✏️</button>
                        <button class="action-btn delete-btn" onclick="deleteSubcategory(${subcategory.id})" title="删除子分类">🗑️</button>
                    </div>
                </div>
                </li>
            `;
        }

        // 显示添加子分类弹窗
        function showAddSubcategoryModal() {
            currentSubcategoryId = null;
            selectedIcon = '📁';
            initEmojiSearch('#emoji-search', '#emoji-selector', '#emoji-selector-empty', selectedIcon);
            $('#subcategoryModalTitle').text('添加子分类');
            $('#subcategory-name').val('');
            $('#subcategory-description').val('');
            $('#subcategory-icon-picker').hide();
            $('#subcategoryModal').modal('show');
        }

        // 编辑子分类
        function editSubcategory(id, name, description, icon) {
            currentSubcategoryId = id;
            selectedIcon = icon;
            initEmojiSearch('#emoji-search', '#emoji-selector', '#emoji-selector-empty', selectedIcon);
            $('#subcategoryModalTitle').text('编辑子分类');
            $('#subcategory-name').val(name);
            $('#subcategory-description').val(description);
            $('#subcategory-icon-picker').hide();
            $('#subcategoryModal').modal('show');
        }

        // 通过ID编辑子分类（从DOM获取数据）
        function editSubcategoryById(id) {
            const subcategoryItem = $(`.category-item[data-id="${id}"]`);
            const name = subcategoryItem.data('name') || subcategoryItem.find('.category-name').text();
            const icon = subcategoryItem.data('icon') || '📁';
            const description = subcategoryItem.data('desc') || '';
            editSubcategory(id, name, description, icon);
        }

        // 切换图标选择器显示/隐藏
        function toggleSubcategoryIconPicker() {
            const iconPicker = document.querySelector('.icon-selector');
            if (iconPicker.style.display === 'none' || !iconPicker.style.display) {
                iconPicker.style.display = 'block';
            } else {
                iconPicker.style.display = 'none';
            }
        }

        // 选择图标
        function selectSubcategoryIcon(icon) {
            selectedIcon = icon;
            document.querySelectorAll('.icon-option').forEach(option => {
                if (option.getAttribute('data-icon') === icon) {
                    option.classList.add('selected');
                } else {
                    option.classList.remove('selected');
                }
            });
        }

        // 初始化图标选择器点击事件
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.icon-option').forEach(option => {
                option.addEventListener('click', function() {
                    const icon = this.getAttribute('data-icon');
                    selectSubcategoryIcon(icon);
                });
            });
        });

        // 点击其他地方关闭图标选择器
        $(document).click(function(e) {
            if (!$(e.target).closest('.icon-selector').length) {
                $('#subcategory-icon-picker').hide();
            }
        });

        // 创建子分类
        function createSubcategory() {
            const name = $('#subcategory-name').val().trim();
            const description = $('#subcategory-description').val().trim();

            if (!name) {
                showMessage('请输入子分类名称', 'error');
                return;
            }

            const data = {
                name: name,
                description: description,
                icon: selectedIcon,
                _token: $('meta[name="csrf-token"]').attr('content')
            };

            $.post(`{{ route('user.subcategories.store', [$book->id, $category->id]) }}`, data, function(response) {
                if (response.success) {
                $('#subcategoryModal').modal('hide');
                showSuccess('子分类创建成功');
                loadSubcategories();
            } else {
                showError(response.message || '创建失败', response);
                }
            }).fail(function(e) {
                showError(e.responseJSON.message || '网络错误，请重试', e.responseJSON);
            });
        }

        // 更新子分类
        function updateSubcategory() {
            const name = $('#subcategory-name').val().trim();
            const description = $('#subcategory-description').val().trim();

            if (!name) {
                showMessage('请输入子分类名称', 'error');
                return;
            }

            const data = {
                name: name,
                description: description,
                icon: selectedIcon,
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'PUT'
            };

            $.post(`{{ route('user.subcategories.update', [$book->id, $category->id, '']) }}/${currentSubcategoryId}`, data, function(response) {
                if (response.success) {
                $('#subcategoryModal').modal('hide');
                showSuccess('子分类更新成功');
                loadSubcategories();
            } else {
                showError(response.message || '更新失败');
                }
            }).fail(function(e) {
                showError(e.responseJSON.message || '网络错误，请重试', e.responseJSON);
            });
        }

        // 删除子分类
        function deleteSubcategory(id) {
            // 直接使用DELETE请求检查是否有记录需要迁移
            const checkData = {
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'DELETE',
                check_only: true
            };

            $.post(`{{ route('user.subcategories.destroy', [$book->id, $category->id, ':id']) }}`.replace(':id', id), checkData, function(response) {
                // 如果没有交易记录和自动交易记录，直接删除
                if (response.success && !response.has_transactions && !response.has_auto_transactions) {
                    confirmDeleteSubcategory(id);
                }
            }).fail(function(e) {
                const responseData = e.responseJSON;

                // 检查是否需要迁移
                if (responseData && responseData.require_migration) {
                    showSubcategoryMigrationModal(
                        id, 
                        responseData.transaction_count, 
                        responseData.other_subcategories,
                        responseData.auto_transaction_count,
                        responseData.total_count
                    );
                } else {
                    showError(responseData.message || '网络错误，请重试');
                }
            });
        }

        // 确认删除子分类
        function confirmDeleteSubcategory(id) {
            if (!confirm('确定要删除这个子分类吗？删除后无法恢复。')) {
                return;
            }

            const data = {
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'DELETE'
            };

            $.post(`{{ route('user.subcategories.destroy', [$book->id, $category->id, ':id']) }}`.replace(':id', id), data, function (response) {
                if (response.success) {
                    showSuccess('子分类删除成功');
                    loadSubcategories();
                } else {
                    showError(response.message || '删除失败');
                }
            }).fail(function (e) {
                const responseData = e.responseJSON;

                // 检查是否需要迁移
                if (responseData && responseData.require_migration) {
                    showSubcategoryMigrationModal(id, responseData.transaction_count, responseData.other_subcategories);
                } else {
                    showError(responseData.message || '网络错误，请重试');
                }
            });
        }

        // 初始化拖拽排序
        function initSortable() {
            const listElement = document.getElementById('subcategory-list');
            if (listElement && sortable) {
                sortable.destroy();
            }

            if (listElement) {
                sortable = Sortable.create(listElement, {
                    handle: '.drag-handle',
                    animation: 150,
                    onEnd: function(evt) {
                        updateSubcategorySort();
                    }
                });
            }
        }

        // 更新子分类排序
        function updateSubcategorySort() {
            const sortData = [];
            $('#subcategory-list .category-item').each(function(index) {
                sortData.push({
                    id: $(this).data('id'),
                    sort: index + 1
                });
            });

            const data = {
                sort_data: sortData,
                _token: $('meta[name="csrf-token"]').attr('content')
            };

            $.post(`{{ route('user.subcategories.sort', [$book->id, $category->id]) }}`, data, function(response) {
                if (response.success) {
                showSuccess('排序更新成功');
            } else {
                showError('排序更新失败');
                loadSubcategories(); // 重新加载以恢复原始顺序
            }
        }).fail(function() {
            showError('网络错误，请重试');
            loadSubcategories(); // 重新加载以恢复原始顺序
            });
        }

        // 显示子类别迁移模态框
        function showSubcategoryMigrationModal(subcategoryId, transactionCount, otherSubcategories, autoTransactionCount, totalCount) {
            // 设置消息和当前子类别ID
            let message = '';
            
            if (transactionCount > 0 && autoTransactionCount > 0) {
                message = `该子类别下有 ${transactionCount} 条交易记录和 ${autoTransactionCount} 条自动交易记录，删除前需要将这些记录迁移到其他子类别。`;
            } else if (transactionCount > 0) {
                message = `该子类别下有 ${transactionCount} 条交易记录，删除前需要将这些记录迁移到其他子类别。`;
            } else if (autoTransactionCount > 0) {
                message = `该子类别下有 ${autoTransactionCount} 条自动交易记录，删除前需要将这些记录迁移到其他子类别。`;
            } else {
                message = `该子类别下有 ${totalCount || transactionCount} 条记录，删除前需要将这些记录迁移到其他子类别。`;
            }
            
            $('#subcategory-migration-message').text(message);
            $('#source-subcategory-id').val(subcategoryId);

            // 清空并填充目标分类下拉框
            const targetCategorySelect = $('#target-category-select');
            targetCategorySelect.empty();
            targetCategorySelect.append('<option value="">请选择目标分类</option>');

            // 加载所有分类
            $.get(`{{ route('user.categories.data', $book->id) }}`, function(response) {
                if (response.success && response.categories) {
                    // 过滤掉当前分类
                    const otherCategories = response.categories.filter(category => category.id != {{ $category->id }});

                    if (otherCategories.length > 0) {
                        // 添加当前分类作为第一个选项
                        targetCategorySelect.append(`<option value="{{ $category->id }}">{{ $category->icon }} {{ $category->name }} (当前分类)</option>`);

                        // 添加其他分类
                        otherCategories.forEach(category => {
                            targetCategorySelect.append(`<option value="${category.id}">${category.icon || ''} ${category.name}</option>`);
                        });

                        // 当选择分类变化时，加载对应的子分类
                        targetCategorySelect.off('change').on('change', function() {
                            const selectedCategoryId = $(this).val();
                            if (selectedCategoryId) {
                                loadSubcategoriesForMigration(selectedCategoryId, subcategoryId);
                            } else {
                                $('#target-subcategory-container').hide();
                                $('#target-subcategory-select').empty().append('<option value="">请选择目标子类别</option>');
                            }
                        });

                        // 默认选择当前分类并加载其子分类
                        targetCategorySelect.val({{ $category->id }}).trigger('change');

                        // 显示模态框
                        $('#subcategory-migration-modal').modal('show');
                    } else {
                        showError('没有可用的目标分类进行迁移');
                    }
                } else {
                    showError('加载分类失败');
                }
            }).fail(function() {
                showError('网络错误，请重试');
            });
        }

        // 加载分类下的子分类用于迁移
        function loadSubcategoriesForMigration(categoryId, sourceSubcategoryId) {
            $.get(`{{ route('user.subcategories.data', [$book->id, ':id']) }}`.replace(':id', categoryId), function(response) {
                if (response.success && response.subcategories) {
                    // 过滤掉源子分类
                    const otherSubcategories = response.subcategories.filter(subcategory => subcategory.id != sourceSubcategoryId);

                    const targetSubcategorySelect = $('#target-subcategory-select');
                    targetSubcategorySelect.empty();
                    targetSubcategorySelect.append('<option value="">请选择目标子类别</option>');

                    if (otherSubcategories.length > 0) {
                        otherSubcategories.forEach(subcategory => {
                            targetSubcategorySelect.append(`<option value="${subcategory.id}">${subcategory.icon || ''} ${subcategory.name} </option>`);
                        });

                        $('#target-subcategory-container').show();
                    } else {
                        $('#target-subcategory-container').hide();
                        showMessage('该分类下没有可用的目标子类别', 'warning');
                    }
                } else {
                    $('#target-subcategory-container').hide();
                }
            }).fail(function() {
                $('#target-subcategory-container').hide();
                showError('加载子分类失败');
            });
        }

        // 迁移并删除子类别
        function migrateAndDeleteSubcategory() {
            const sourceSubcategoryId = $('#source-subcategory-id').val();
            const targetCategoryId = $('#target-category-select').val();
            const targetSubcategoryId = $('#target-subcategory-select').val();

            if (!sourceSubcategoryId || !targetCategoryId) {
                showError('请选择目标分类');
                return;
            }

            if ($('#target-subcategory-container').is(':visible') && !targetSubcategoryId) {
                showError('请选择目标子类别');
                return;
            }

            const data = {
                target_category_id: targetCategoryId,
                _token: $('meta[name="csrf-token"]').attr('content')
            };

            // 如果选择了子分类，则添加到请求数据中
            if (targetSubcategoryId) {
                data.target_subcategory_id = targetSubcategoryId;
            }

            $.post(`{{ route('user.subcategories.migrate', [$book->id, $category->id, ':id']) }}`.replace(':id', sourceSubcategoryId), data, function(response) {
                if (response.success) {
                    // 显示包含交易记录和自动交易记录迁移信息的成功消息
                    showSuccess(response.message || '子类别迁移并删除成功');
                    $('#subcategory-migration-modal').modal('hide');
                    loadSubcategories();
                } else {
                    showError(response.message || '迁移失败');
                }
            }).fail(function(e) {
                const responseData = e.responseJSON;
                showError(responseData?.message || '网络错误，请重试');
            });
        }

        // 使用全局消息提示函数
        // 注意：此处不再定义showMessage函数，而是使用base.blade.php中定义的全局函数
    </script>
@endpush
